我的Bilibili频道:香芋派Taro
我的个人博客:taropie0224.github.io(阅读体验更佳)
我的公众号:香芋派的烘焙坊
我的音频技术交流群:1136403177
我的个人微信:JazzyTaroPie

https://leetcode-cn.com/problems/palindrome-linked-list/

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution
{
public:
bool isPalindrome(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
{
return true;
}
ListNode *slow = head;
ListNode *fast = head;
ListNode *pre = head;
ListNode *temp = nullptr;
while (fast != nullptr && fast->next != nullptr)
{
pre = slow;
slow = slow->next;
fast = fast->next->next;
pre->next = temp;
temp = pre;
}
if (fast != nullptr)
{
slow = slow->next;
}
while (pre != nullptr && slow != nullptr)
{
if (pre->val != slow->val)
{
return false;
}
pre = pre->next;
slow = slow->next;
}
return true;
}
};

思路

新建一对快慢指针,fast到头时,slow在中间,于此同时,还要新建一个反转的链表,注意其中反转链表的写法,可以背下来